<?php
/**
 * @file $HeadURL: tryproduct.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2015-3-21 上午11:18:17 $
 * @brief 
 */
namespace haibao\cms\data;


use haibao\cms\business\control\PublicController;
class TryProduct extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\TryProduct');
	}
	
	public function getTryProductById($tryId){
		return $this->getOneById($tryId);
	}

	public function getTryProductByQuery($query){
		return $this->getAll($query);
	}
	
	public function getTryProductByIds($tryIds){
	    $sql = 'select Id,Title,BrandId,BrandName,Amount,Specifications,Price,PicId,PublishDate,ApplyStartTime,ApplyEndTime,ExperienceStartTime,ExperienceEndTime,LastModifyTime from TryProduct where Id in ('.implode(',',$tryIds).')';
	    $data = $this->query($sql,$tryIds);
	    $row = array();
	    while($data->fetch_assoc()){
	        $result['Title'] = $data->getData('Title');
	        $result['BrandId'] = $data->getData('BrandId');
	        $result['BrandName'] = $data->getData('BrandName');
	        $result['Amount'] = $data->getData('Amount');
	        $result['Specifications'] = $data->getData('Specifications');
	        $result['Price'] = $data->getData('Price');
	        $result['PicId'] = $data->getData('PicId');
	        $result['PublishDate'] = $data->getData('PublishDate');
	        $result['ApplyStartTime'] = $data->getData('ApplyStartTime');
	        $result['ApplyEndTime'] = $data->getData('ApplyEndTime');
	        $result['ExperienceStartTime'] = $data->getData('ExperienceStartTime');
	        $result['ExperienceEndTime'] = $data->getData('ExperienceEndTime');
	        $result['LastModifyTime'] = $data->getData('LastModifyTime');
	        $row[$data->getData('Id')] = $result;
	    }
	    return $row;
	}
	
	/**
	 * 根据试用产品ID（array）查询产品申请数量
	 * @param array $tryIds
	 * @return array
	 */
	public function getApplyNumByIds($tryIds){
		$arrId = (array)$tryIds;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $arrId));
		$sql = "select TryId,count(*) as num from TryApply where TryId in({$str}) group by TryId order by TryId desc";
		$result = $this->query($sql, $arrId);
		$data = array();
		while ($result->fetch_assoc()){
			$data[$result->getData('TryId')] = $result->getData('num');
		}
		return $data;
	}
	
	/**
	 * 添加试用产品
	 * @param \haibao\cms\model\data\TryProduct $model
	 */
	public function addTryProduct($model){
		$this->beginTranscation();
		try {
			$this->add($model);
			
			$tryId = $model->Id;
			$this->addTryProperty( $tryId );
			$this->addContent( $model );
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 修改试用产品发布状态
	 */
	public function updateTryProductStatus($tryIdArr, $published){
		$inStr = preg_replace('/(\d+)/', '%s', implode(',', (array)$tryIdArr));
		
		$sql = 'update TryProduct set Published=%s where Id in('.$inStr.')';
		array_unshift($tryIdArr, $published);
		$this->query($sql, $tryIdArr);
	}
	
	/**
	 * @param \haibao\cms\model\data\TryProduct $model
	 */
	public function addTryProperty($tryId){
		$sql = 'insert into TryProperty(TryId, PV) values (%s, %s)';
		$this->query($sql, array($tryId, 0));
	}
	
	/**
	 * @param \haibao\cms\model\data\TryProduct $model
	 */
	public function addContent($model){
		$sql = 'insert into TryContent(TryId, Content) values (%s, %s)';
		$this->query($sql, array(
				$model->Id, $model->Content
		));
	}
	
	public function updateContent($model){
		$sql = 'update TryContent set Content=%s where TryId=%s limit 1';
		$this->query($sql, array(
				$model->Content, $model->Id
		));
	}
	
	public function getTryContetById($tryId){
		$content = "";
		$sql = "select Content from TryContent where tryId=%s";
		$result = $this->query($sql, array($tryId));
		while ($result->fetch_assoc()){
			$content = $result->getData('Content');
		}
		return $content;
	}
	
	/**
	 * 更新试用
	 * @param \haibao\cms\model\data\TryProduct $model
	 */
	public function updateTryProductById($model){
		if(!$model->Id){
			return false;
		}
		$this->beginTranscation();
		try {
			$this->updateById($model->Id, array(
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_TITLE => $model->Title,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_INTRODUCE => $model->Introduce,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_BRAND_ID => $model->BrandId,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_BRAND_NAME => $model->BrandName,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_AMOUNT => $model->Amount,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_SPECIFICATIONS => $model->Specifications,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_PRICE => $model->Price,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_PIC_ID => $model->PicId,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_PUBLISHED => $model->Published,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_PUBLISHDATE => $model->PublishDate,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_APPLY_START_TIME => $model->ApplyStartTime,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_APPLY_END_TIME => $model->ApplyEndTime,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_EXPERIENCE_START_TIME => $model->ExperienceStartTime,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_EXPERIENCE_END_TIME => $model->ExperienceEndTime,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_LAST_MODIFY_TIME => $model->LastModifyTime,
				\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_LAST_MODIFY_USER => $model->LastModifyUser,
			    \haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_BOSS_USER_ID => $model->BossUserId,
			    \haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_PRODUCT_MODEL_ID => $model->ProductModelId,
			    \haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_PRODUCT_NAME =>  $model->ProductName,
			)); 
			
			$this->updateContent($model);
			
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 删除试用产品（软删除）
	 */
	public function deleteTryProductById($tryIds, $userId){
		if(!$tryIds){
			return false;
		}
		$this->updateById($tryIds, array(
			\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_STATUS => \haibao\cms\model\data\TryProduct::STATUS_DISABLE,
			\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_LAST_MODIFY_TIME => date('Y-m-d H:i:s'),
			\haibao\cms\model\filter\TryProduct::CONDITION_FIELD_NAME_LAST_MODIFY_TIME => $userId,
		));
	}
	
	/**
	 * 合作品牌
	 */
	public function getTryBrandList(){
		$sql = "select * from TryProduct where `Status`=%s and Published=%s and BrandId!=0 group by BrandId order by LastModifyTime desc limit 5";
		$result = $this->query($sql, array(
			\haibao\cms\model\data\TryProduct::STATUS_ENABLE, \haibao\cms\model\data\TryProduct::PUBLISHED_YES
		));
		$brandIdArr = array();
		while ($result->fetch_assoc()){
			array_push($brandIdArr, $result->getData('BrandId'));
		}
		
		$str = preg_replace('/(\d+)/', '%s', join(',', $brandIdArr));
		
		$result = $this->query("select a.Id,a.TagId,a.ImgId,a.NameCN,a.NameEN,b.FansNum from Brand as a left join BrandStatisticalInfo as b on a.Id=b.BrandId where a.Status=%s and a.ImgId<>0 and a.Id in(".$str.")", 
				array_merge((array)\haibao\cms\model\data\Brand::STATUS_ENABLE, $brandIdArr)
			);
		
		$brandArr = array();
		while ($row = $result->fetch_assoc()){
			$tagInfo = \haibao\cms\business\Tag::getTagById($result->getData('TagId'), false);
			$temp = array(
				'Id' => $result->getData('Id'),
				'BrandId' => $tagInfo->TopicId,
				'PicId' => $result->getData('ImgId'),
				'NameCN' => $result->getData('NameCN'),
				'NameEN' => $result->getData('NameEN'),
				'FansNum' => $result->getData('FansNum'),
			);
			array_push($brandArr, $temp);
		}
		return $brandArr;
	}
	
	/**
	 * 根据品牌ID查询相关试用产品
	 */
	public function getProductByBrand($brandId, $limit = 20){
	    $sql = "select * from TryProduct where BrandId=%s order by Id desc ";
	    if($limit){
	        $sql .= " limit $limit";
	    }
	    $result = $this->query($sql, array($brandId));
	    $brandArr = array();
	    while ($row = $result->fetch_assoc()){
	        array_push($brandArr, $row);
	    }
	    return $brandArr;
	}
	
	public function getTryProductBesidesById($tryId){
        $tryList = array();
        $time = new \DateTime();
        $sql = "select * from TryProduct where Id!=%s AND Status = 1 AND Published = 1 AND ApplyStartTime<=%s AND ApplyEndTime>=%s ORDER BY PublishDate Desc";
        $result = $this->query($sql, array($tryId,$time,$time));
        while ($row = $result->fetch_assoc()){
             $tryList[$row['Id']] = $row;  
        }
        return $tryList;
	}
	
	public function getTryProductList(){
	    $sql = 'SELECT * FROM TryProduct WHERE `Status` = %s AND Published = %s ORDER BY PublishDate Desc LIMIT 2';
	    $result = $this->query($sql,array(\haibao\cms\model\data\TryProduct::STATUS_ENABLE, \haibao\cms\model\data\TryProduct::PUBLISHED_YES));
	    $tryList = array();
	    while ($row = $result->fetch_assoc()){
	       $tryList[$row['Id']] = $row;    
	    }
	    return $tryList;
	}
}